package team.seekers.hula.system.ratelimit.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import team.seekers.hula.system.ratelimit.limiter.RequestRateLimiter;

import java.util.List;

@Slf4j
@Configuration
public class RateLimiterConfig {

    @Bean
    public RedisScript redisRequestRateLimiterScript() {
        DefaultRedisScript redisScript = new DefaultRedisScript();
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("scripts/request_rate_limiter.lua")));
        redisScript.setResultType(List.class);
        return redisScript;
    }
    @Bean
    @Primary
    @ConditionalOnMissingBean
    public RequestRateLimiter globalRateLimiter(@Qualifier("redisRequestRateLimiterScript") RedisScript<List<Long>> redisScript) {
        return new RequestRateLimiter(redisScript);
    }
}

